package cn.xs.surveypark.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import cn.xs.surveypark.dao.BaseDao;

/**
 * Dao基类实现 
 * @param <T>
 */
@SuppressWarnings("unchecked")
public abstract class BaseDaoImpl<T> implements BaseDao<T>{

	@Resource
	private SessionFactory sf;
	
	private Class<T> clazz;
	
	/**
	 * 用来推算出 泛型 T 的类型
	 */
	public BaseDaoImpl() {
		ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
		clazz = (Class<T>) type.getActualTypeArguments()[0];
//		System.out.println(this.getClass().getName()+"  用来推算出 泛型 T 的类型--- "+this.getClass().getGenericSuperclass().getClass().getName());
//		for (int i = 0; i < type.getActualTypeArguments().length; i++) {
//			System.out.println(type.getActualTypeArguments()[i]);
//		}
	}
	
	public void saveEntity(T t) {
//		System.out.println("Save方法： "+t.getClass().getName());
		sf.getCurrentSession().save(t);
	}

	public void updateEntity(T t) {
		sf.getCurrentSession().update(t);
		
	}

	public void saveOrUpdateEntity(T t) {
		sf.getCurrentSession().saveOrUpdate(t);
		
	}

	public void deleteEntity(T t) {
		sf.getCurrentSession().delete(t);
		
	}

	public void batchEnttyByHQL(String hql, Object... objects) {
		Query q = sf.getCurrentSession().createQuery(hql);
		for (int i = 0; i < objects.length; i++) {
			q.setParameter(i, objects[i]);
		}
		q.executeUpdate();
	}

	//get
	public T getEntity(Integer id) {
		return (T) sf.getCurrentSession().get(clazz, id);
	}

	//load
	public T loadEntity(Integer id) {
		return (T) sf.getCurrentSession().load(clazz, id);
	}

	public List<T> findgetEntityHQL(String hql, Object... objects) {
		Query q = sf.getCurrentSession().createQuery(hql);
		for (int i = 0; i < objects.length; i++) {
			q.setParameter(i, objects[i]);
		}
		return q.list();
	}

}
